package com.atmilan.quartz.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.atmilan.quartz.utils.product.DelloglioProductUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.atmilan.quartz.constant.Constants;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.SyncStatusEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.dto.delloglio.DelloglioProductResDTO;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.SystemConfig;
import com.atmilan.quartz.model.entity.delloglio.DelloglioProduct;
import com.atmilan.quartz.model.entity.delloglio.DelloglioProductSku;
import com.atmilan.quartz.service.IDelloglioProductService;
import com.atmilan.quartz.service.IDelloglioProductSkuService;
import com.atmilan.quartz.service.IDelloglioSyncService;
import com.atmilan.quartz.service.IStoreProductService;
import com.atmilan.quartz.service.ISystemConfigService;
import com.atmilan.quartz.utils.RedisUtil;
import com.atmilan.quartz.utils.source.SourceDelloglioProductUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class DelloglioSyncServiceImpl implements IDelloglioSyncService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ISystemConfigService systemConfigService;
    @Autowired
    IDelloglioProductService delloglioProductService;
    @Autowired
    IDelloglioProductSkuService delloglioProductSkuService;
    @Autowired
    IStoreProductService storeProductService;
    @Autowired
    SourceDelloglioProductUtil sourceDelloglioProductUtil;
    @Autowired
    DelloglioProductUtil delloglioProductUtil;

    @Override
    public Boolean syncDelloglioProduct() {
        //数据清空
        try {
			delloglioProductService.deleteAll();
			delloglioProductSkuService.deleteAll();
			long millis = System.currentTimeMillis();
			DelloglioProductResDTO delloglioProductResDTO = delloglioProductUtil.getDelloglioProductList();
			if (null == delloglioProductResDTO) {
			    log.info("--------------- delloglio获取商品接口请求失败 ---------------");
			    return true;
			}
			log.info("--------------- delloglio远程抓取数据, 总共: {} 条, 总耗时: {} 分  ---------------", delloglioProductResDTO.getNumber(), (int) ((System.currentTimeMillis() - millis) / 1000 / 60));
			saveGoods(delloglioProductResDTO);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return true;
    }

    /**
     * 商品源数据保存
     *
     * @param delloglioProductResDTO
     */
    private void saveGoods(DelloglioProductResDTO delloglioProductResDTO) {
        List<DelloglioProduct> productList = new ArrayList<>();
        List<DelloglioProductSku> skuList = new ArrayList<>();
        delloglioProductResDTO.getProducts().forEach(product->{
            DelloglioProduct delloglioProduct = new DelloglioProduct();
            BeanUtils.copyProperties(product,delloglioProduct);
            productList.add(delloglioProduct);
            product.getItems().forEach(sku->{
                DelloglioProductSku delloglioProductSku = new DelloglioProductSku().setProductId(product.getProductId());
                BeanUtils.copyProperties(sku,delloglioProductSku);
                skuList.add(delloglioProductSku);
            });
        });
        delloglioProductService.saveBatch(productList);
        delloglioProductSkuService.saveBatch(skuList);
    }

    @Override
    public Boolean pushDelloglioProduct() {
        try {
            //当次更新少于1千条, 则不更新, 并且重新拉取
            int count = delloglioProductService.count();
            if(1000 > count){
                systemConfigService.update(Wrappers.<SystemConfig>lambdaUpdate()
                        .eq(SystemConfig :: getName, Constants.DELLOGLIO_SYNC_STATUS)
                        .set(SystemConfig :: getFormId, SyncStatusEnum.PUSH)
                        .set(SystemConfig :: getUpdateTime, new Date())
                );
                log.info("--------------- Delloglio商品源数据, 少于规定条数, 不进行下发, 总条数为: {} ---------------", count);
                return false;
            }
            //将所有Delloglio商品更新状态置为未更新
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct :: getIsEurope, ProductTypeEnum.DELLOGLIO.getCode())
                    .set(StoreProduct :: getUpdateFlag, false)
            );
            //商品更新操作
            int pageNo = 1;
            int pageSize = 100;
            int maxPage = (count + pageSize - 1) / pageSize;
            log.info("--------------- 开始分页查询DELLOGLIO商品源数据, 本次更新总条数为: {} ---------------", count);

            long millis = System.currentTimeMillis();
            while (pageNo <= maxPage) {
                try {
                    PageHelper.startPage(pageNo, pageSize);
                    List<DelloglioProduct> delloglioProducts = delloglioProductService.list();
                    PageInfo<DelloglioProduct> pageInfo = PageInfo.of(delloglioProducts);
                    List<DelloglioProduct> products = pageInfo.getList();
                    buildProduct(products);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                log.info("--------------- DELLOGLIO下发商品到数据库, 当前页数: {}, 总页数: {}, 耗时: {} 分 ---------------", pageNo, maxPage, (int) ((System.currentTimeMillis() - millis) / 1000 / 60));
                pageNo++;
            }
            // 图搜删除
            storeProductService.delSeachImage(ProductTypeEnum.DELLOGLIO);
            // 下架所有未更新数据
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct::getIsEurope, ProductTypeEnum.DELLOGLIO.getCode())
                    .eq(StoreProduct::getUpdateFlag, false)
                    .eq(StoreProduct :: getIsShow, true)
                    .eq(StoreProduct :: getIsDel, false)
                    .set(StoreProduct::getIsShow, false)
                    .set(StoreProduct::getStock, 0)
                    .set(StoreProduct::getLastPushTime, new Date())
                    .set(StoreProduct::getIsTusou, false)
                    );
            // 下架所有sku库存
            storeProductService.downloadSku(ProductTypeEnum.DELLOGLIO.getCode());
            
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 商品构建处理
     * @param products 商品集合
     */
    private void buildProduct(List<DelloglioProduct> products) {
        try {
            for (DelloglioProduct product : products) {
                if(StringUtils.isBlank(product.getProductName())){
                    log.info("--------------- 该商品: {} 名称为空, 不进行下放 ---------------",product.getProductId());
                    continue;
                }
                if(StringUtils.isBlank(product.getPicture())){
                    log.info("--------------- 该商品: {} 没有图片, 不进行下放 ---------------",product.getProductId());
                    continue;
                }
                List<DelloglioProductSku> skus = delloglioProductSkuService.list(Wrappers.<DelloglioProductSku>lambdaQuery()
                        .eq(DelloglioProductSku::getProductId, product.getProductId())
                        .isNotNull(DelloglioProductSku::getItemSize)
                        .gt(DelloglioProductSku::getStock, 0)
                );
                List<DelloglioProductSku> exceptionList = new ArrayList<>();
                for (DelloglioProductSku productSku : skus) {
                    if(StringUtils.isBlank(productSku.getSupplyPrice()) || new BigDecimal(productSku.getSupplyPrice()).compareTo(BigDecimal.ZERO) < 1){
                        log.info("--------------- 该商品id:{}, sku: {} 售价异常, 不进行下放 ---------------",productSku.getProductId(),productSku.getItemId());
                        exceptionList.add(productSku);
                    }
                }
                skus.removeAll(exceptionList);
                if (CollectionUtils.isEmpty(skus)) {
                    continue;
                }
                // 库存计算
                int stock = 0;
                for (DelloglioProductSku sku : skus) {
                    stock += Integer.parseInt(sku.getStock());
                }
                // 构建实体
                StoreProductCrmebRequest storeProductCrmebRequest = sourceDelloglioProductUtil.buildDelloglioProduct(product, skus);
                // 数据保存
                StoreProduct storeProduct = storeProductService.getByBarCode(storeProductCrmebRequest.getBarCode(), storeProductCrmebRequest.getSuppliersId(), storeProductCrmebRequest.getKeyword());
                boolean crmebUpdate = true;
                if (null != storeProduct && null != storeProduct.getLastPushTime()) {
                    long txyye = (System.currentTimeMillis() - storeProduct.getLastPushTime().getTime()) / 1000 / 60;
                    if (60 > txyye) {
                        log.info("--------------- 该商品: {} 上次Delloglio更新时间: {} 小于一小时, 不进行更新 ---------------", storeProductCrmebRequest.getBarCode(), storeProduct.getLastPushTime());
                        crmebUpdate = false;
                        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                                .eq(StoreProduct::getId, storeProduct.getId())
                                .set(StoreProduct::getUpdateFlag, true)
                        );
                    }
                }
                if (crmebUpdate) {
                    storeProductService.saveOtProduct(storeProductCrmebRequest, storeProduct, stock);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }
}
